package com.elitel.frame.web.serverinfo.dto;

import com.elitel.frame.web.acservicefilterfield.entity.AcServiceFilterFields;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * @author m
 */
@Data
@Slf4j
public class ServerInfoDTO implements Serializable {

    /**
     * 服务基础信息
     */
    private ServerConfigDTO basicConfig;
    /**
     * 查询字段
     */
    private List<ServerQueryFieldDTO> queryFieldList;
    /**
     * 展示字段
     */
    private List<ServerShowFieldDTO> showFieldList;
    /**
     * 过滤字段
     */
    private List<AcServiceFilterFields> filterFields;
    /**
     * 其他信息
     */
    private Map<String, Object> customInfo;

    /**
     * 获取继承者实例
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public <T extends ServerInfoDTO> T getSuccessor(Class<T> clazz) {
        try {
            T t = clazz.newInstance();
            t.setBasicConfig(basicConfig);
            t.setQueryFieldList(queryFieldList);
            t.setShowFieldList(showFieldList);
            t.setFilterFields(filterFields);
            if (customInfo != null) {
                // 将otherInfo中的属性值复制到t中
                for (Field declaredField : t.getClass().getDeclaredFields()) {
                    // 根据set方法给属性赋值
                    try {
                        String methodName = "set" + declaredField.getName().substring(0, 1).toUpperCase() + declaredField.getName().substring(1);
                        Method method = t.getClass().getMethod(methodName, declaredField.getType());
                        method.invoke(t, customInfo.get(declaredField.getName()));
                    } catch (Exception e) {
                        log.error("复制属性值失败", e);
                    }
                }
            }
            return t;
        } catch (Exception e) {
            log.error("获取继承类实例失败");
            throw new RuntimeException(e);
        }
    }
}
